<template>
	<view style="width: 100%; height: 100%">
		<uni-ec-canvas
			class="uni-ec-canvas"
			canvas-id="record1"
			ref="chart"
			:ec="ec"
		></uni-ec-canvas>
	</view>
</template>

<script>
import uniEcCanvas from '@/components/uni-ec-canvas/uni-ec-canvas.vue'
import * as echarts from '@/components/uni-ec-canvas/echarts.min.js'
//添加功能需要下载5.12版本，不然会报错
export default {
	name: 'chart',
	components: {
		uniEcCanvas
	},
	data() {
		return {
			ec: {
				//是否懒加载, 将 lazyLoad 设为 true 后，需要手动初始化图表
				myChart: null,
				lazyLoad: true
			},
			loading: false
		}
	},
	props: {
		option: {
			type: Object
		},
		formatterFn: {
			type: Function 
		}
	},
	watch: {
		option: {
			handler(newVal, oldVal) {
				this.initChart()
			},
			deep: true
		}
	},
	mounted() {
		this.initChart()
	},
	methods: {
		initChart() {
			let option = {}
			option = this.option
			if (this.option.showChart) {
				option['title'] = {
					text: '暂无数据',
					show: true,
					x: 'center',
					y: 'center',
					textStyle: {
						fontFamily: 'Manteka',
						fontSize: '12',
						fontWeight: 'normal',
						color: '#666'
					}
				}
				// option = {
				//     title: {
				//         text: '暂无数据',
				//         show:true,
				//         x: 'center',
				//         y: 'center',
				//         textStyle: {
				//             fontFamily: 'Manteka',
				//             fontSize: '12',
				//             fontWeight: 'normal',
				//             color: '#666'
				//         }
				//     }
				// }
			} else {
				// option = this.option
				option['title'] = {
					show: false
				}
			}

			if (!this.myChart) {
				this.$refs['chart'].init((canvas, width, height, dpr) => {
					this.myChart = echarts.init(canvas, null, {
						width,
						height,
						devicePixelRatio: dpr // new
					})
					if (option['tooltip'] ) {
						// option['tooltip']['position'] = this.tooltipPosition
                        if(option.tooltip.formatterFn){
					        option['tooltip']['formatter'] = this.formatterFn
                        }
					}
					this.myChart.setOption(option)
					this.myChart.on('click', (params) => {
						this.$emit('chartClick', { ...params })
					})
					return this.myChart
				})
			} else {
				if (this.option.showChart) {
					this.myChart.clear()
				}
				if (option['tooltip']) {
					// option['tooltip']['position'] = this.tooltipPosition
                    if(option.tooltip.formatterFn){
                        option['tooltip']['formatter'] = this.formatterFn
                    }
				}
				this.myChart.setOption(option)
			}
		},
		tooltipPosition(point, params, dom, rect, size) {
			return [point[0], '0']
		}
	},
	beforeDestroy() {
		if (this.myChart) {
			this.myChart = null
		}
	}
}
</script>

<style></style>
